#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2019-06-24 10:07
# @Author   : BYF
# file      : request.py
# @version  :

import os
import sys
import json
import requests
from lefull.common import log
from lefull.conf.config import Config


class Request:
    def __init__(self):
        self.config = Config()
        self.host = self.config.private_debug

    def check_url(self, url):
        """
        对URL做一个初步的检查
        :param url:
        :return:
        """
        if not url.startswith("http"):
            log.error("url错误，请检查~！当前url为：{url}/n".format(url=url))
            return False

    def request_get(self, url, headers, payload, name):
        """
        自定义get请求，完成URL拼接和日志记录
        :param url:
        :param headers:
        :param params:
        :return:
        """
        url = self.config.private_debug + url
        self.check_url(url)

        try:
            response = requests.get(url=url, headers=headers, params=payload)
            log.case_log(name, url, headers, payload, response.text)
            return response
        except requests.RequestException as e:
            log.error(e)
        except Exception as e:
            log.error(e)

    def request_post(self, url, headers, payload, payload_type, name):
        """
        自定义post请求，完成URL拼接和日志记录
        :param url:
        :param headers:
        :param payload:
        :param payload_type:参数类型；dict -> 表示字典，json -> 表示json字符串，
        :return:
        """
        # url = self.config.private_debug + url
        self.check_url(url)

        try:
            if payload_type is None or payload_type == "dict":
                response = requests.post(url=url, headers=headers, data=payload)
            elif payload_type == "json":
                response = requests.post(url=url, headers=headers, json=payload)
            log.case_log(name, url, headers, payload, response.text)
            return response
        except requests.RequestException as e:
            log.error(e)
        except Exception as e:
            log.error(e)


if __name__ == '__main__':
    pass
